<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="博文标题" prop="articleTitle">
        <el-input
          v-model="queryParams.articleTitle"
          placeholder="请输入博文标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="浏览量" prop="viewCount">
        <el-input
          v-model="queryParams.viewCount"
          placeholder="请输入浏览量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞数" prop="likeCount">
        <el-input
          v-model="queryParams.likeCount"
          placeholder="请输入点赞数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['weblog:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['weblog:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['weblog:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['weblog:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="articleTitle" />
      <el-table-column label="封面" align="center" prop="articleCover" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" align="center" prop="viewCount" />
      <el-table-column label="点赞数" align="center" prop="likeCount" />
      <el-table-column label="是否加密" align="center" prop="viewStatus" />
      <el-table-column label="是否推荐[0:否，1:是]" align="center" prop="recommendStatus" />
      <el-table-column label="是否启用评论[0:否，1:是]" align="center" prop="commentStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['weblog:article:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['weblog:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章管理对话框 -->
    <el-dialog :title="title" v-model="open"  append-to-body class="myDialog">
      <el-form ref="articleRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="标题" prop="articleTitle">
          <el-input v-model="form.articleTitle" placeholder="请输入博文标题" />
        </el-form-item>

        <el-form-item label="内容">
          <mavon-editor ref="mavonEditorRef" v-model="form.articleContent" :ishljs="true" @imgAdd="imgAdd" style="width: 100%" @imgDel="imgDel"/>
        </el-form-item>

        <el-form-item label="封面" prop="articleCover">
          <image-upload-url v-model="form.imageUrl"  v-model:ossid="form.articleCover" :limit="1"/>
        </el-form-item>


          <el-form-item label="分类" prop="sortId">
            <el-select
              v-model="form.sortId"
              @change="getLabelList"
              placeholder="请选择分类类型"
            >
              <el-option
                v-for="item in sortList"
                :key="item.id"
                :label="item.sortName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>


        <el-form-item label="标签" prop="sortId">
          <el-select
            v-model="form.labelId"
            placeholder="请选择标签"
          >
            <el-option
              v-for="item in labelList"
              :key="item.id"
              :label="item.labelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="是否推荐" prop="recommendStatus">
          <el-switch
            v-model="form.recommendStatus"
            active-value="1"
            inactive-value="0"
            class="ml-2"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>


        <el-form-item label="启用评论" prop="commentStatus">
          <el-switch
            v-model="form.commentStatus"
            active-value="1"
            inactive-value="0"
            class="ml-2"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>


        <el-form-item label="是否加密" prop="viewStatus">
          <el-select
            v-model="form.viewStatus"
            placeholder="Select"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in blog_show_type"
              :key="item.value"
              :label="item.label"
              :value="parseInt(item.value)"
            />
          </el-select>
<!--          <el-switch-->
<!--            v-model="form.viewStatus"-->
<!--            active-value="1"-->
<!--            inactive-value="0"-->
<!--            class="ml-2"-->
<!--            style="&#45;&#45;el-switch-on-color: #13ce66; &#45;&#45;el-switch-off-color: #ff4949"-->
<!--          />-->
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="form.viewStatus == '3'">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="提示" prop="tips" v-if="form.viewStatus == '3'">
          <el-input v-model="form.tips" placeholder="请输入提示" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/weblog/article";
import { listLabel } from "@/api/weblog/label";
import { listSort } from "@/api/weblog/sort";
import {getCurrentInstance, nextTick, onMounted, ref} from "vue";
import ImageUploadUrl from "@/components/ImageUploadUrl/index.vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {getToken} from "@/utils/auth";
import {deleteWithUrl} from "@/api/system/oss";
import {handleThemeStyle} from "@/utils/theme";
import useSettingsStore from "@/store/modules/settings";

const { proxy } = getCurrentInstance();

const articleList = ref([]);
const labelList = ref([]);
const sortList = ref([]);

const mavonEditorRef = ref();
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/system/oss/upload"); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const { blog_show_type } = proxy.useDict("blog_show_type");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sortId: undefined,
    labelId: undefined,
    articleTitle: undefined,
    viewCount: undefined,
    likeCount: undefined,
    viewStatus: undefined,
  },
  rules: {
    id: [
      // { required: true, message: "id不能为空", trigger: "blur" }
    ],
    sortId: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    labelId: [
      { required: true, message: "标签不能为空", trigger: "change" }
    ],
    articleCover: [
      { required: true, message: "封面不能为空", trigger: "blur" }
    ],
    articleTitle: [
      { required: true, message: "博文标题不能为空", trigger: "blur" }
    ],
    articleContent: [
      { required: true, message: "博文内容不能为空", trigger: "blur" }
    ],
    viewCount: [
      // { required: true, message: "浏览量不能为空", trigger: "blur" }
    ],
    likeCount: [
      // { required: true, message: "点赞数不能为空", trigger: "blur" }
    ],
    viewStatus: [
      // { required: true, message: "是否加密不能为空", trigger: "change" }
    ],
    tips: [
      // { required: true, message: "提示不能为空", trigger: "blur" }
    ],
    recommendStatus: [
      { required: true, message: "是否推荐不能为空", trigger: "change" }
    ],
    commentStatus: [
      { required: true, message: "是否启用评论不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文章管理列表 */
function getList() {
  loading.value = true;
  listArticle(queryParams.value).then(response => {
    articleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    sortId: null,
    labelId: null,
    articleCover: null,
    imageUrl:null,
    articleTitle: null,
    articleContent: "",
    viewCount: null,
    likeCount: null,
    viewStatus: 0,
    password: null,
    tips: null,
    recommendStatus: 0,
    commentStatus: 0,
    createTime: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("articleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function removeAria() {
  nextTick(() => {
    const icons = document.querySelectorAll('.op-icon');
    // 遍历这些元素并移除 aria-hidden 属性
    icons.forEach(icon => {
      icon.removeAttribute('aria-hidden');
    });
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文章管理";
  removeAria();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getArticle(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    getLabelList(form.value.sortId);

    open.value = true;
    title.value = "修改文章管理";
    removeAria()
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除文章管理编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delArticle(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

function getLabelList(value){
  console.log(value,"getLabelList")
  listLabel({sortId:value}).then(res=>{
    labelList.value = res.rows
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('weblog/article/export', {
    ...queryParams.value
  }, `article_${new Date().getTime()}.xlsx`)
}

function imgAdd(pos, file) {
  let formdata = new FormData();
  formdata.append("file", file);
  uploadFileRequest(uploadImgUrl.value, formdata).then((res) => {
    console.log(res)
    let json = res.data;
    if (json.code == 200) {
      mavonEditorRef.value.$imglst2Url([[pos, json.data.url]]);
    } else {
      ElMessage({ type: json.code, message: json.data});
    }
  });
}

function imgDel( $file){
  deleteWithUrl($file[0])
}

const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data',
        ...headers.value
    }
  });
}

onMounted(()=>{
  listSort({}).then(res=>{
    sortList.value = res.rows
  })
  getList();
})


</script>

<style lang="scss" >
@import "@/assets/styles/mixin.scss";
@import "@/assets/styles/variables.module.scss";


.myDialog {
  width: calc(100% - #{$base-sidebar-width}) !important; /* 保持原有的宽度设置 */
  height: 100vh; /* 设置高度为100% */
  margin-top: 0px !important;
  margin-right: 0px !important;
  margin-bottom: 0px !important;
  margin-left: $base-sidebar-width !important;
  //position: fixed; /* 或者使用absolute，取决于您的需求 */
  top: 0; /* 确保对话框从顶部开始 */
  right: 0; /* 确保对话框与屏幕右侧距离为0 */
  overflow: auto; /* 如果内容过多，允许滚动 */
  /* 可能还需要其他样式，如背景色、边框、z-index等 */
}
.myDialog:not(.is-fullscreen) {
  margin-top: 0vh !important;
}
</style>
